﻿using Hotel.Application.Dics.Dto;
using Hotel.Application.Dics;
using Hotel.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hotel.Repositories;
using AutoMapper;
using Newtonsoft.Json;
using System.Linq.Expressions;
using SqlSugar;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Serialization;
using Hotel.Utility;
using Quartz.Util;

namespace Hotel.Application.Dics
{
    public class DicService : BaseService<Dic, DicCreateUpdateDto, DicListDto>, IDicService
    {
        private readonly IRepository<DicType> repository1;
        private readonly IRepository<Dic> repository;

        public DicService(
            IRepository<DicType> repository1,
            IRepository<Dic> repository,
            IDistributedCache<DicListDto> cache
            ) : base(repository)
        {
            this.repository1 = repository1;
            this.repository = repository;
            this.cache = cache;
        }

        public async Task<ResultDto<bool>> CheckName(DicCreateUpdateDto dto)
        {            
            return new ResultDto<bool>
            {
                code = State.Success,
                data = await repository.AnyAsync(m => m.TypeId == dto.TypeId && (m.DicName == dto.DicName || m.DicValue == dto.DicValue || m.DicCode == dto.DicCode) && m.DicId != dto.DicId)
            };
        }

        public override async Task<ResultDto<List<DicListDto>>> QueryAsync()
        {
            var list = await cache.GetOrAddAsync(
                nameof(Dic), 
                async () => {
                    var list = await repository1.QueryAsQueryable().InnerJoin(repository.QueryAsQueryable(), (a, b) => a.TypeId == b.TypeId)
                     .Select((a, b) => new DicListDto { },true).ToListAsync();
                   return list;
                }, 
                new Microsoft.Extensions.Caching.Distributed.DistributedCacheEntryOptions 
                {
                    AbsoluteExpiration = DateTimeOffset.UtcNow.AddHours(2),
                });

            return new ResultDto<List<DicListDto>> { data = list };
        }

        public async Task<List<DicListDto>> QueryByCacheAsync(Func<DicListDto, bool> expression)
        {
            return (await QueryAsync()).data.Where(expression).ToList();            
        }

        [HttpGet]
        public async Task<List<DicListDto>> QueryByCacheAsync(string TypeCode)
        {
            return (await QueryAsync()).data.Where(m => m.TypeCode == TypeCode).ToList();
        }
    }

}
